package org.dawning.shop.category.service;

import lombok.extern.log4j.Log4j;
import org.dawning.shop.category.entity.BaseCategory;
import org.dawning.shop.category.entity.Attribute;
import org.dawning.shop.category.entity.Type;
import org.dawning.shop.category.repertory.BaseCategoryRepository;
import org.dawning.shop.category.vo.CategoryVO;
import org.dawning.shop.core.base.BaseResult;
import org.dawning.shop.core.base.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Created by L on 2017/6/12.
 */
@Service
@Log4j
public class BaseCategoryService extends BaseService {

    @Autowired
    private BaseCategoryRepository baseCategoryRepository;

    /**
     * @param name 分类名
     * @param code 分类code
     * @param pid  父ID
     * @param sort 排序
     * @return
     */
    public BaseResult addCategory(String pid, String name, String code, int sort) {
        //数据库里面的对象
        BaseCategory baseCategoryResult;
        try {
            //插入的对象
            BaseCategory baseCategory = new BaseCategory();
            baseCategory.preInsert();
            baseCategory.setCategoryCode(code);
            baseCategory.setCategoryName(name);
            baseCategory.setSort(sort);
            if (StringUtils.isEmpty(pid)) {
                baseCategoryResult = baseCategoryRepository.save(baseCategory);
            } else {
                BaseCategory parentCate = baseCategoryRepository.findOneById(pid);
                if (parentCate == null) {
                    return return400("fail");
                }
                baseCategory.addAncestorIds(parentCate.getAncestorIds());
                baseCategory.addAncestorId(pid);
                baseCategory.setParentId(pid);
                baseCategoryResult = baseCategoryRepository.save(baseCategory);
            }
            if (baseCategoryResult != null) {
                return return200("success", baseCategoryResult);
            } else {
                return return400("fail");
            }
        } catch (Exception e) {
            log.info("error", e);
            return return500("error");
        }
    }

    /**
     * @param id 分类ID
     * @return
     */
    public BaseResult getCategory(String id) {
        try {
            BaseCategory baseCategory = baseCategoryRepository.findOneById(id);
            if (baseCategory != null) {
                CategoryVO vo = CategoryVO.getVO(baseCategory);
                List<BaseCategory> list = baseCategoryRepository.findAllByAncestorIdsContaining(id);
                List<CategoryVO> listVo = CategoryVO.getVOList(list);
                vo = recursionChild(vo, listVo);
                return return200("success", vo);
            } else {
                return return400("fail");
            }
        } catch (Exception e) {
            log.info("error", e);
            return return500("error");
        }
    }

    /**
     * 递归处理子分类
     *
     * @param category
     * @param list
     */
    private CategoryVO recursionChild(CategoryVO category, List<CategoryVO> list) {
        for (CategoryVO baseCategory : list) {
            if (baseCategory.getParentId().equals(category.getId())) {
                category.addChildCate(baseCategory);
            }
        }
        if (category.getChildrenList() != null && category.getChildrenList().size() > 0) {
            for (int i = 0; i < category.getChildrenList().size(); i++) {
                recursionChild(category.getChildrenList().get(i), list);
            }
        }
        return category;
    }

    /**
     * @param id 分类名
     * @return
     */
    public BaseResult deleteCategory(String id) {
        try {
            BaseCategory baseCategory = baseCategoryRepository.findOneById(id);
            if (baseCategory != null) {
                List<BaseCategory> children = baseCategoryRepository.findAllByAncestorIdsContaining(id);
                for (BaseCategory child : children) {
                    child.logicDelete();
                    baseCategoryRepository.save(child);
                }
                baseCategory.logicDelete();
                baseCategoryRepository.save(baseCategory);
                return return200("success", null);
            } else {
                return return400("fail");
            }
        } catch (Exception e) {
            log.info("error", e);
            return return500("error");
        }
    }

    /**
     * @param id   分类ID
     * @param name 分类名
     * @param code 分类code
     * @param sort 排序
     * @return
     */
    public BaseResult updateCategory(String id, String name, String code, int sort) {
        try {
            BaseCategory baseCategory = baseCategoryRepository.findOneById(id);
            if (baseCategory == null) {
                return return400("fail");
            }
            if (!StringUtils.isEmpty(code)) {
                baseCategory.setCategoryCode(code);
            }
            if (!StringUtils.isEmpty(name)) {
                baseCategory.setCategoryName(name);
            }
            if (sort > 0) {
                baseCategory.setSort(sort);
            }
            baseCategory.preUpdate();
            BaseCategory baseCategorys = baseCategoryRepository.save(baseCategory);
            if (baseCategorys != null) {
                return return200("success", baseCategorys);
            } else {
                return return400("fail");
            }
        } catch (Exception e) {
            log.info("error", e);
            return return500("error");
        }

    }

    /**
     * 添加类型信息
     *
     * @param id          分类ID
     * @param typeName    类型名
     * @param typeCode    类型code
     * @param sort        排序
     * @return
     */
    public BaseResult addType(String id, String typeName, String typeCode, int sort) {
        try {
            BaseCategory category = baseCategoryRepository.findOneById(id);
            if (category != null) {
                Type type = new Type(typeName, typeCode, sort);
                category.addType(type);
                category = baseCategoryRepository.save(category);
                if (category != null) {
                    return return200("success", category);
                }
            }
            return return400("fail");
        } catch (Exception e) {
            log.info("error", e);
            return return500("error");
        }
    }

    /**
     * 添加属性类型信息
     *
     * @param id          分类ID
     * @param typeName    类型名
     * @param typeCode    类型code
     * @param sort        排序
     * @return
     */
    public BaseResult updateType(String id, String typeName, String typeCode, int sort) {
        try {
            BaseCategory category = baseCategoryRepository.findOneById(id);
            if (category != null) {
                for (Type type : category.getTypeList()) {
                    if (type.getTypeCode().equals(typeCode)) {
                        type.setTypeName(typeName);
                        type.setSort(sort);
                    }
                }
                BaseCategory resultCate = baseCategoryRepository.save(category);
                if (resultCate != null) {
                    return return200("success", resultCate);
                }
            }
            return return400("fail");
        } catch (Exception e) {
            log.info("error", e);
            return return500("error");
        }
    }

    /**
     * 删除类型
     *
     * @param id
     * @param code
     * @return
     */
    public BaseResult deleteType(String id, String code) {
        try {
            BaseCategory category = baseCategoryRepository.findOneById(id);
            if (category != null) {
                for (Type type : category.getTypeList()) {
                    if (type.getTypeCode().equals(code)) {
                        category.getTypeList().remove(type);
                        break;
                    }
                }
                category = baseCategoryRepository.save(category);
                if (category != null) {
                    return return200("success", category);
                }
            }
            return return400("fail");
        } catch (Exception e) {
            log.info("error", e);
            return return500("error");
        }
    }


    /**
     * 添加属性信息
     *
     * @param id       分类ID
     * @param typeCode 类型code
     * @param name     属性名
     * @param code     属性code
     * @param sort     排序
     * @return
     */
    public BaseResult addAttribute(String id, String typeCode, String name, String code, int sort) {
        try {
            BaseCategory category = baseCategoryRepository.findOneById(id);
            if (category != null) {
                Attribute attribute = new Attribute(name, code, sort);
                for (Type type : category.getTypeList()) {
                    if (type.getTypeCode().equals(typeCode)) {
                        type.addAttributeList(attribute);
                        break;
                    }
                }
                category = baseCategoryRepository.save(category);
                if (category != null) {
                    return return200("success", category);
                }
            }
            return return400("fail");
        } catch (Exception e) {
            log.info("error", e);
            return return500("error");
        }
    }

    /**
     * 获取属性信息
     *
     * @param id 分类ID
     */
    public BaseResult getAttribute(String id) {
        try {
            BaseCategory category = getAttributes(id);
            if (category != null) {
                return return200("success", category);
            }
            return return400("fail");
        } catch (Exception e) {
            log.info("error", e);
            return return500("error");
        }
    }

    /**
     * 获取属性信息
     *
     * @param id 分类ID
     */
    public BaseCategory getAttributes(String id) {
        try {
            BaseCategory category = baseCategoryRepository.findOneById(id);
            if (category != null) {
                if (category.getAncestorIds()!=null){
                    for (String pid : category.getAncestorIds()) {
                        BaseCategory parentBaseCategory = baseCategoryRepository.findOneById(pid);
                        category.addTypes(parentBaseCategory.getTypeList());
                    }
                }
                return category;
            }
            return null;
        } catch (Exception e) {
            log.info("error", e);
            return null;
        }
    }

    /**
     * 删除属性
     *
     * @param id
     * @param typeCode
     * @param code
     * @return
     */
    public BaseResult deleteAttribute(String id, String typeCode, String code) {
        try {
            BaseCategory category = baseCategoryRepository.findOneById(id);
            if (category != null) {
                boolean isPro = false;
                for (Type type : category.getTypeList()) {
                    if (isPro) break;
                    if (type.getTypeCode().equals(typeCode)) {
                        for (Attribute attribute : type.getAttributeList()) {
                            if (code.equals(attribute.getCode())) {
                                type.getAttributeList().remove(attribute);
                                isPro = true;
                                break;
                            }
                        }
                    }
                }
                BaseCategory baseCategory = baseCategoryRepository.save(category);
                return return200("success", baseCategory);
            }
            return return400("fail");
        } catch (Exception e) {
            log.info("error", e);
            return return500("error");
        }
    }
}
